﻿using System.Xml;

using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

namespace KubertSoft.MSBuildTasks.Subversion.Svn
{
    /// <summary>
    /// The base class for client tasks based on svn.exe.
    /// </summary>
    public abstract class SvnClientTaskBase : SvnTaskBase
    {
        /// <summary>
        /// Gets or sets the document helper.
        /// </summary>
        /// <value>The document helper.</value>
        protected internal XmlDocumentHelper XmlDocumentHelper { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="SvnClientTaskBase"/> class.
        /// </summary>
        protected SvnClientTaskBase()
        {
            XmlDocumentHelper = new XmlDocumentHelper();
        }

        /// <summary>
        /// Gets the XML output.
        /// </summary>
        /// <value>The XML output.</value>
        [Output]
        public ITaskItem Xml
        {
            get { return OutputTaskItems.GetRequired(TaskItemNames.Xml); }
        }

            /// <summary>
        /// Gets the name of the executable file to run.
        /// </summary>
        /// <value>The name of the executable file to run.</value>
        protected override string ToolName
        {
            get { return "svn.exe"; }
        }

        /// <summary>
        /// Builds the parameters command line.
        /// </summary>
        internal protected override void BuildCommandLine()
        {
            CommandLine.AppendSwitch(CommandLineSwitches.Xml);
        }

        /// <summary>
        /// Logs the events from text output.
        /// </summary>
        /// <param name="singleLine">The single line.</param>
        /// <param name="messageImportance">The message importance.</param>
        protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance)
        {
            XmlDocumentHelper.AppendLine(singleLine);
            base.LogEventsFromTextOutput(singleLine, messageImportance);
        }

        /// <summary>
        /// Runs after execute.
        /// </summary>
        protected internal override void InitializeOutputParameters()
        {
            try
            {
                XmlDocumentHelper.Build();
            }
            catch (XmlException ex)
            {
                Log.LogErrorFromException(ex);
            }
            OutputTaskItems.RegisterTaskItem(TaskItemNames.Xml, new TaskItem(XmlDocumentHelper.Text));
        }
    }
}


